package cn.hxzy.commonUser.controller;


import cn.hxzy.common.Result;
import cn.hxzy.common.util.RandomUtil;
import cn.hxzy.commonUser.service.MsmService;
import cn.hxzy.commonUser.service.UserService;
import cn.hxzy.entity.userEntity.User;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import org.springframework.stereotype.Controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author ao.Li
 * @since 2023-06-23
 */
@CrossOrigin
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private MsmService msmService;

    @Autowired
    @Qualifier("redis")
    private RedisTemplate<String, Object> redisTemplate;



    //    远程调用 马奎志
//    @GetMapping("/{phone}")
//    public User selectOneByPhone(@PathVariable String phone) {
//        return userService.selectOneByPhone(phone);
//
//    远程调用 马奎志

    @GetMapping("/selectOneByPhone/{phone}")
    public User selectOneByPhone(@PathVariable("phone") String phone){
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("user_phone",phone);
        User user = userService.getOne(wrapper);
        if (user != null){
           return user;
        }
        return null;
    }

    @GetMapping("/UpdateUserRealNameAuthentication/{phone}/{certification}")
    public Boolean UpdateUserRealNameAuthentication(@PathVariable("phone")String phone,@PathVariable("certification")int certification){
        UpdateWrapper<User> wrapper = new UpdateWrapper<>();
        wrapper.set("user_certification",certification);
        wrapper.eq("user_phone",phone);
        boolean b = userService.update(wrapper);
        return b;
    }

    //发送短信的方法
    @GetMapping("/sendCode/{userPhone}")
    public Result sendMsm(@PathVariable String userPhone) throws JsonProcessingException {
        //1 从redis获取验证码，如果获取到直接返回
        Object code = redisTemplate.opsForValue().get(userPhone);
        String s = String.valueOf(code);//利用工具转化对象类型\

        if (!s.equals("null")) {
            Integer codesss = Integer.parseInt(s);
            return Result.error().code(codesss).message("已发送过验证码，请检查");
        }
        //2 如果redis获取 不到，进行阿里云发送
        //生成随机值，传递阿里云进行发送
        code = RandomUtil.getFourBitRandom();
        Map<String, Object> param = new HashMap<>();
        param.put("code", code);
        //调用service发送短信的方法
        boolean isSend = msmService.send(param, userPhone);
        if (isSend) {
            //发送成功，把发送成功验证码放到redis里面
            //设置有效时间
            redisTemplate.opsForValue().set(userPhone, code, 5, TimeUnit.MINUTES);
            return Result.ok().message("短信发送成功！").data(param);
        } else {
            return Result.error().message("短信发送失败");
        }

    }

    /**
     * 司机登录
     * @param user
     * @return
     */
    @PostMapping("loginDriver")
    public Result loginDriver(@RequestBody User user) {
        if (user.getRoleId().equals("1")) {
            Result login = userService.login(user);
            return login;
        }
        return Result.error().message("请输入司机账户！");
    }

    /**
     * 货主登录
     * @param user
     * @return
     */
    @PostMapping("loginOwner")
    public Result loginOwner(@RequestBody User user) {
        if (user.getRoleId().equals("2")) {
            Result login = userService.login(user);
            return login;
        }
        return Result.error().message("请输入货主账户！");
    }

    /**
     * 司机验证码登录
     * @param user
     * @return
     */
    @PostMapping("loginByCodeDriver")
    public Result loginByCodeDriver(@RequestBody User user) {
        if (user.getRoleId().equals("2")) {
            Result login = userService.loginByCode(user);
            return login;
        }
        return Result.error().message("请输入司机账户！");
    }

    /**
     * 货主验证码登录
     *
     * @param user
     * @return
     */
    @PostMapping("loginByCodeOwner")
    public Result loginByCodeOwner(@RequestBody User user) {
        if (user.getRoleId().equals("2")) {
            Result login = userService.loginByCode(user);
            return login;
        }
        return Result.error().message("请输入货主账户！");
    }

    /**
     * 退出登录
     *
     * @return
     */
    @GetMapping("logout")
    public Result logout() {
        Result logout = userService.logout();
        return logout;
    }

    @GetMapping("status")
    public Result status(HttpServletRequest request, HttpServletResponse response) {
        Result status = userService.status(request, response);
        return status;
    }

    /**
     * 注册
     *
     * @param user
     * @return
     */
    @PostMapping("registered")
    public Result registered(@RequestBody User user) {
        Result registered = userService.registered(user);
        return registered;
    }


    /**
     * 修改密码
     *
     * @param userId
     * @param oldPwd
     * @param newPwd
     * @return
     */
    @GetMapping("/updatePwdById/{userId}/{oldPwd}/{newPwd}")
    public Result updatePwdById(@PathVariable String userId, @PathVariable String oldPwd, @PathVariable String newPwd) {
        Boolean flag = userService.updatePwdById(userId, oldPwd, newPwd);

        if (flag) return Result.ok().message("修改密码成功");
        return Result.error().message("修改密码失败");
    }

    @PostMapping("/loginByPwd")
    public Result loginByPwd(@RequestBody User user) {
        User user1 = userService.loginByPwd(user);
        if (user1 != null) return Result.ok().message("登录成功").data("userId",user1.getUserId());
        return Result.error().message("登录失败");
    }
}

